package com.guoguo.api;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseController;
import com.guoguo.base.SMSEnumN;
import com.guoguo.base.StaticResource;
import com.guoguo.base.StaticResourceN;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.UserOther;
import com.guoguo.entity.Users;
import com.guoguo.enums.SMSEnum;
import com.guoguo.enums.UsersEnum;
import com.guoguo.service.IUserExtService;
import com.guoguo.service.IUsersService;
import com.guoguo.utils.HttpClientUtils;
import com.guoguo.utils.JsonUtils;
import com.guoguo.utils.PropertyUtils;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.SMSHxUtils;
import com.guoguo.utils.TokenUtils;
import com.guoguo.utils.UUIDUtils;
import com.guoguo.utils.nowpay.PhoneFormatCheckUtils;
import com.guoguo.utils.nowpay.VerifyNumber;

/**
 * Created by Administrator on 2017/8/15 0015.
 */
@RestController
@RequestMapping("/api")
public class AppLoginController extends BaseController {
    private Logger log = LoggerFactory.getLogger(AppLoginController.class);
    @Resource
    private IUsersService usersService;

    @Resource
    private IUserExtService iUserExtService;

    private String password;

    /**
     * 用户登录
     *
     * @param nickName  用户昵称
     * @param userName  用户名
     * @param userpwd   用户密码
     * @param loginType 登录类型 (0:帐号登录，1：第三方登录)
     * @param icon      用户头像
     * @param phoneType 手机类型
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONObject findUser(HttpServletRequest request, @RequestParam String userName, @RequestParam String nickName,
                               @RequestParam String userpwd, @RequestParam int loginType, @RequestParam String icon,
                               @RequestParam int phoneType) {

        boolean flag = false;
        Users users = null;
        if (loginType == 0) {
            //普通登录时，用户名和密码不能为空
            if (userName == null || "".equals(userName)) {
                return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), null, UsersEnum.LOGIN_USER_ERROR.getValue());
            }
            if (userpwd == null || "".equals(userpwd)) {
                return returnResult(UsersEnum.LOGIN_PWD_ERROR.getId(), null, UsersEnum.LOGIN_PWD_ERROR.getValue());
            }
            users = usersService.findUser(userName, userpwd);
        } else if (loginType == 1) {
            //第三方登录时，用户名不能为空
            if (userName == null || "".equals(userName)) {
                return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), null, UsersEnum.LOGIN_USER_ERROR.getValue());
            }
            try {
                nickName = new String(nickName.getBytes("iso-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            users = usersService.findUsers(userName, nickName, icon, Integer.valueOf(request.getHeader("appId")), phoneType);
        }
        Map<String, String> data = new HashMap<String, String>();
        if (users != null) {
            RedisUtils redisUtils = RedisUtils.getInstance();

            //当token验证通过，返回原token。没有token时，会创建一个新的token。
            if (redisUtils.exists(StaticResource.SYS_TOKEN_KEY + request.getHeader("token"))) {
                data.put("token", String.valueOf(request.getHeader("token")));
            } else {
                //生成token
                data.put("token", TokenUtils.getToken());
                redisUtils.set(StaticResource.SYS_TOKEN_KEY + data.get("token"), userName);
                //token有效期一月
                redisUtils.expire(StaticResource.SYS_TOKEN_KEY + data.get("token"), 3600 * 24 * 30);
            }
            data.put("userId", users.getUserId());
            request.getSession().setAttribute("users", users);
            return returnResult(UsersEnum.LOGIN_SUCCESS.getId(), data, UsersEnum.LOGIN_SUCCESS.getValue());
        } else {
            return returnResult(UsersEnum.LOGIN_ERROR.getId(), null, UsersEnum.LOGIN_ERROR.getValue());
        }

    }

    /**
     * 游客登录
     *
     * @param request
     * @param Mac
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/guestLogin", method = RequestMethod.POST)
    public JSONObject guestLogin(HttpServletRequest request, @RequestParam String Mac) {

        if (Mac == null || "".equals(Mac)) {
            return returnResult(UsersEnum.MAC_NULL.getId(), null, UsersEnum.MAC_NULL.getValue());
        }
        Map<String, String> data = new HashMap<String, String>();
        RedisUtils redisUtils = RedisUtils.getInstance();
        if (redisUtils.exists(StaticResource.SYS_TOKEN_KEY + request.getHeader("token"))) {
            data.put("token", String.valueOf(request.getHeader("token")));
        } else {
            data.put("token", TokenUtils.getToken());
            redisUtils.set(StaticResource.SYS_TOKEN_KEY + data.get("token"), Mac);
        }
        return returnResult(UsersEnum.LOGIN_SUCCESS.getId(), data, UsersEnum.LOGIN_SUCCESS.getValue());

    }

    /**
     * 用户注册
     *
     * @param phone
     * @param valiCode
     * @param userpwd
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JSONObject userRegister(@RequestParam String userName, @RequestParam String phone, @RequestParam String
            valiCode, @RequestParam int phonetype, @RequestParam String userpwd, HttpServletRequest request) {
        Map<String, Object> data = new HashMap();
        RedisUtils redisUtils = RedisUtils.getInstance();
        String isScrUser = null;
        Integer addCount = null;
        //验证码是否过期
        if (redisUtils.exists(StaticResource.SYS_VALICODE_REG + phone)) {
            String valicode = redisUtils.getString(StaticResource.SYS_VALICODE_REG + phone);
            //验证码错误
            if (!valicode.equals(valiCode)) {
                //注册失败
                return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), data, UsersEnum.REGISTER_VALICODE_ERROR.getValue());
            } else {
                int usersNum = usersService.count(phone);
                if (usersNum == 0) {

                    Users user = new Users();
                    UserExt userExt = new UserExt();
                    UserOther userOther = new UserOther();
                    user.setUserId(UUIDUtils.getUUID());
                    user.setUsername(userName);
                    user.setUserpwd(userpwd);
                    user.setPhone(phone);
                    if (PhoneFormatCheckUtils.isPhoneLegal(userName)) {
                        user.setNickname(VerifyNumber.verifyNumber(userName));
                    } else {
                        user.setNickname(userName);
                    }
                    user.setAppId(Integer.valueOf(request.getHeader("appId")));
                    user.setPhoneType(phonetype);
                    int num = usersService.insertUsers(user);
                    userExt.setUserId(user.getUserId());
                    userExt.setEmail(null);
                    userExt.setPhone(user.getPhone());
                    Date now = new Date();
                    userExt.setRegistered(now);
                    userExt.setCreateTime(now);
                    userExt.setSex(false);
                    userExt.setIcon(null);
                    userExt.setBuyCount(0);

                    userExt.setBuySurplus(0);
                    userExt.setIsMember(false);
                    userExt.setMemType(null);
                    userExt.setMoney(null);
                    userExt.setPoint(0L);

                    userOther.setUserId(user.getUserId());
                    userOther.setExp(0);
                    userOther.setLevel(1);

                    //查询注册的用户是否被邀请过,当天邀请人次数小于10次
                    isScrUser = usersService.selectUserIsHaveSrcUser(phone);
                    if (StringUtils.isNotBlank(isScrUser) && !isScrUser.equals("null")) {
                        //userExt.setPoint(1000L);
                    	iUserExtService.insertUserExt(userExt);
                        addCount = iUserExtService.addSrcUserPoint(isScrUser,phone);
                    }else{
                    	iUserExtService.insertUserExt(userExt);
                    }
                    usersService.insertUserOther(userOther);

                    Map<String, String> params = new HashedMap();
                    params.put("userName", userName);
                    params.put("nickName", user.getNickname());
                    params.put("loginType", "0");
                    params.put("icon", "");
                    params.put("appId", String.valueOf(user.getAppId()));
                    params.put("phoneType", String.valueOf(phonetype));
                    params.put("userpwd", user.getUserpwd());

                    //注册成功
                    //调用login
                    String loginApiUrl = PropertyUtils.getProperty("api.properties", "api.domainName") + "/api/login";
                    log.info("===============>>>>>>    loginApiUrl : " + loginApiUrl);
                    String result = HttpClientUtils.doPost(loginApiUrl, params, "utf-8");
                    JSONObject resultJson = JSON.parseObject(result);
                    return resultJson;
                } else {
                    //用户已经存在
                    return returnResult(UsersEnum.LOGIN_EXITS_USERS.getId(), "", UsersEnum.LOGIN_EXITS_USERS.getValue());
                }
            }
        } else {
            //验证码过期
            return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), data, UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());
        }

    }

    /**
     * 发送验证码短信
     * 验证码在缓存里存在5分钟
     *
     * @param phoneNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendViliCode", method = RequestMethod.POST)
    public JSONObject sendViliCode(@RequestParam String phoneNo, @RequestParam int smsType) {
        String valiCode = String.valueOf(Double.valueOf((Math.random() * 9 + 1) * 100000).intValue());
        String message = new String();
        String redisKey = new String();
        Integer phoneCount = null;
        boolean isPhone;
        if (StringUtils.isBlank(phoneNo)) {
            return returnResult(UsersEnum.PHONE_EMPTY_ERROR.getId(), "", UsersEnum.PHONE_EMPTY_ERROR.getValue());
        }
        String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        isPhone = Pattern.matches(REGEX_MOBILE, phoneNo);
        if (isPhone) {
            if (smsType == 0) {
                message = MessageFormat.format(SMSEnum.SMS_TEMPLATE_VALICODE.getValue(), valiCode);
                /**
                 * 注册时，进行用户帐号验证。
                 * 修改密码时不验证用户
                 */
                if (smsType == 0) {
                    int userObj = usersService.count(phoneNo);
                    if (userObj != 0) {
                        //用户已经存在
                        return returnResult(UsersEnum.LOGIN_EXITS_USER.getId(), "", UsersEnum.LOGIN_EXITS_USER.getValue());
                    }
                }
            }

            if (smsType == 0) {
                redisKey = StaticResource.SYS_VALICODE_REG + phoneNo;
            } else if (smsType == 1) {
                message = MessageFormat.format(SMSEnum.SMS_TEMPLATE_PASSWORD.getValue(), valiCode);
                redisKey = StaticResource.SYS_VALICODE_PWD + phoneNo;
            } else if (smsType == 2) {
                phoneCount = usersService.selectCountByPhone(phoneNo);
                if (phoneCount > 0) {
                    return returnResult(UsersEnum.PHONE_EXIST.getId(), "", UsersEnum.PHONE_EXIST.getValue());
                } else {
                    message = MessageFormat.format(SMSEnumN.SMS_TEMPLATE_BINDPHONE.getValue(), valiCode);
                    redisKey = StaticResourceN.SYS_VALICODE_PHONE + phoneNo;
                }
            } else if (smsType == 3) {
                message = MessageFormat.format(SMSEnumN.SMS_TEMPLATE_RESETPWD.getValue(), valiCode);
                redisKey = StaticResourceN.SYS_VALICODE_RESETPWD + phoneNo;
            }
            RedisUtils redisUtils = RedisUtils.getInstance();
            redisUtils.set(redisKey, valiCode);
            //设置验证码过期时间
            redisUtils.expire(redisKey, 300);
            SMSHxUtils.sendMassage(phoneNo, message);
            return returnResult(UsersEnum.SMS_SEND_SUCCESS.getId(), "", UsersEnum.SMS_SEND_SUCCESS.getValue());
        } else {
            return returnResult(UsersEnum.PHONE_ERROE.getId(), "", UsersEnum.PHONE_ERROE.getValue());
        }

    }


    /**
     * 找回密码
     *
     * @param userName 用户名
     * @param userpwd  密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserpwd", method = RequestMethod.POST)
    public JSONObject updateUserpwd(@RequestParam String userName, @RequestParam String
            valiCode, @RequestParam String userpwd) {

        Map<String, Object> data = new HashMap<String, Object>();
        RedisUtils redisUtils = RedisUtils.getInstance();

        if (userName == null) {
            return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), data, UsersEnum.LOGIN_USER_ERROR.getValue());
        } else {
            //验证码是否过期
            if (redisUtils.exists(StaticResource.SYS_VALICODE_PWD + userName)) {
                String valicode = redisUtils.getString(StaticResource.SYS_VALICODE_PWD + userName);
                //验证码错误
                if (!valicode.equals(valiCode)) {
                    return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), data, UsersEnum.REGISTER_VALICODE_ERROR.getValue());
                }

                return returnResult(UsersEnum.UPDATEUSERPWD_SUCCESS.getId(), data, UsersEnum.UPDATEUSERPWD_SUCCESS.getValue());
            } else {
                return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), data, UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());
            }
        }
    }

    /**
     * 用户设置
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userSet", method = RequestMethod.POST)
    public JSONObject userSet(@RequestParam Map<String, String> model) {
        log.info("into AppLoginController userSet method");
        String userId = model.get("userId");
        Map<String, String> data = new HashMap<String, String>();
        try {
            data = usersService.userSet(userId);
            if (data.get("status").equals("207")) {
                data.remove("status");
                return returnResult(UsersEnum.LOGIN_EMPTY_ERROR.getId(), data, UsersEnum.LOGIN_EMPTY_ERROR.getValue());//用户id为空
            } else if (data.get("status").equals("210")) {
                data.remove("status");
                return returnResult(UsersEnum.LOGIN_NOT_USER.getId(), data, UsersEnum.LOGIN_NOT_USER.getValue());//用户不存在
            } else {
                data.remove("status");
                return JsonUtils.returnObject(200, data, "true");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonUtils.returnObject(201, null, "false");
        }

    }


    /**
     * 绑定手机短信验证
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bingPhone", method = RequestMethod.POST)
    public JSONObject bingPhone(@RequestParam Map<String, String> model) {
        log.info("into AppLoginController bingPhone method");
        String userId = model.get("userId");
        String phoneNo = model.get("phoneNo");
        String valiCode = model.get("valiCode");
        RedisUtils redisUtils = RedisUtils.getInstance();
        Users users = new Users();
        boolean isSuccess = false;
        try {
            if (StringUtils.isBlank(userId)) {
                return returnResult(UsersEnum.LOGIN_EMPTY_ERROR.getId(), "", UsersEnum.LOGIN_EMPTY_ERROR.getValue());//用户id为空
            } else {
                users = usersService.selectByPrimaryKey(userId);
                if (users == null) {
                    return returnResult(UsersEnum.LOGIN_NOT_USER.getId(), "", UsersEnum.LOGIN_NOT_USER.getValue());//用户不存在
                } else {
                    if (StringUtils.isNotBlank(users.getPhone()) && phoneNo.equals(users.getPhone())) {
                        return returnResult(UsersEnum.PHONE_EXIST.getId(), "", UsersEnum.PHONE_EXIST.getValue());//手机号已经绑定
                    }
                }
                //验证码是否过期
                if (redisUtils.exists(StaticResourceN.SYS_VALICODE_PHONE + phoneNo)) {
                    String valicode = redisUtils.getString(StaticResourceN.SYS_VALICODE_PHONE + phoneNo);
                    //验证码错误
                    if (!valicode.equals(valiCode)) {
                        return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), "", UsersEnum.REGISTER_VALICODE_ERROR.getValue());
                    } else {
                        isSuccess = usersService.bingPhone(userId, phoneNo);
                        if (isSuccess) {
                            return returnResult(UsersEnum.BINDPHONE_SUCCESS.getId(), phoneNo, UsersEnum.BINDPHONE_SUCCESS.getValue());
                        } else {
                            return JsonUtils.returnObject(201, null, "false");
                        }
                    }
                } else {
                    return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), "", UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonUtils.returnObject(201, null, "false");
        }

    }


    /**
     * 设置密码
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setPassword", method = RequestMethod.POST)
    public JSONObject setPassword(@RequestParam Map<String, String> model) {
        log.info("into AppLoginController resetPassword method");
        String userId = model.get("userId");
        String userpwd = model.get("userpwd");
        Users users = new Users();
        boolean isSuccess = false;
        //boolean isPassword = false;
        try {
            if (StringUtils.isBlank(userId)) {
                return returnResult(UsersEnum.LOGIN_EMPTY_ERROR.getId(), "", UsersEnum.LOGIN_EMPTY_ERROR.getValue());//用户id为空
            } else {
                //判断密码长度是否在6-16位
                // Integer len = userpwd.length();
                // if( len < 6 || len > 16 ){
                // return returnResult(UsersEnum.PASSWORD_LENGTH_ERROR.getId(),
                // data,
                // UsersEnum.PASSWORD_LENGTH_ERROR.getValue());//密码的长度在6-16位之间
                // }
                // String REGEX_PASSWORD = "^[^\u4e00-\u9fa5]+$";
                // isPassword = Pattern.matches(REGEX_PASSWORD, userpwd);
                // if(!isPassword){
                // return returnResult(UsersEnum.PASSWORD_FORM_ERROR.getId(),
                // data, UsersEnum.PASSWORD_FORM_ERROR.getValue());//密码格式错误
                // }
                users = usersService.selectByPrimaryKey(userId);
                if (users == null) {
                    return returnResult(UsersEnum.LOGIN_NOT_USER.getId(), "", UsersEnum.LOGIN_NOT_USER.getValue());//用户不存在
                }
                isSuccess = usersService.setPassword(userId, userpwd);
                if (isSuccess) {
                    return returnResult(UsersEnum.PASSWORD_SET_SUCCESS.getId(), userpwd, UsersEnum.PASSWORD_SET_SUCCESS.getValue());
                } else {
                    return JsonUtils.returnObject(201, null, "false");
                }

            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonUtils.returnObject(201, null, "false");
        }

    }


    /**
     * 重置密码验证
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public JSONObject resetPassword(@RequestParam Map<String, String> model) {
        log.info("into AppLoginController resetPassword method");
        String userId = model.get("userId");
        String phoneNo = model.get("phoneNo");
        String valiCode = model.get("valiCode");
        RedisUtils redisUtils = RedisUtils.getInstance();
        Users users = new Users();
        boolean isSuccess = false;
        try {
            if (StringUtils.isBlank(userId)) {
                return returnResult(UsersEnum.LOGIN_EMPTY_ERROR.getId(), "", UsersEnum.LOGIN_EMPTY_ERROR.getValue());//用户id为空
            } else {
                users = usersService.selectByPrimaryKey(userId);
                if (users == null) {
                    return returnResult(UsersEnum.LOGIN_NOT_USER.getId(), "", UsersEnum.LOGIN_NOT_USER.getValue());//用户不存在
                }
                //验证码是否过期
                if (redisUtils.exists(StaticResourceN.SYS_VALICODE_RESETPWD + phoneNo)) {
                    String valicode = redisUtils.getString(StaticResourceN.SYS_VALICODE_RESETPWD + phoneNo);
                    //验证码错误
                    if (!valicode.equals(valiCode)) {
                        return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), "", UsersEnum.REGISTER_VALICODE_ERROR.getValue());//验证码错误
                    } else {
                        isSuccess = usersService.resetPassword(userId, phoneNo);
                        if (isSuccess) {
                            return returnResult(UsersEnum.PASSWORD_SUCCESS.getId(), "", UsersEnum.PASSWORD_SUCCESS.getValue());//重置密码验证成功
                        } else {
                            return returnResult(UsersEnum.PASSWORD_SET_ERROR.getId(), "", UsersEnum.PASSWORD_SET_ERROR.getValue());//用户id和用户手机号不匹配
                        }

                    }
                } else {
                    return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), "", UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());//验证码过期
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonUtils.returnObject(201, null, "false");
        }

    }


}
